import ProForm, { ProFormSwitch, ProFormText } from '@ant-design/pro-form';
import { useEffect, useState } from 'react';
import { getRoleOptions } from '../Role/api';
import { getTenantOptions } from '../Tenant/api';
import { Spin, Tag, Tree } from 'antd';
import { GroupEntity } from './entities';
import { InfoForm } from '@/compoments/UserForm/InfoForm';

export const formChildren = (isCreate: boolean) => {

  return (
    <>
      <InfoForm isCreate={isCreate} />
      {isCreate && <PasswordFrom />}
    </>
  );
};

export const PasswordFrom = () => (
  <>
    <ProFormText.Password
      label="密码"
      name="password"
      rules={[
        { required: true, message: '请填写密码' },
      ]}
    />
    <ProFormText.Password
      label="确认密码"
      name="confirmPassword"
      dependencies={['password']}
      rules={[
        { required: true, message: '请填写确认密码' },
        ({ getFieldValue }) => ({
          validator(_, value) {
            if (!value || getFieldValue('password') === value) {
              return Promise.resolve();
            }
            return Promise.reject(new Error('两次密码不一致'));
          },
        }),
      ]}
    />
  </>
)

interface ITreeData {
  title: string;
  key: string;
  isLeaf?: boolean;
  children?: ITreeData[];
  checkable: boolean;
  selectable: boolean;
  pKey: string;
  pTitle: string;
}

export const UpdateRolesForm = () => {

  return (
    <ProForm.Item
      name="groups"
    >
      <RoleFormItem />
    </ProForm.Item>
  )
}

const RoleFormItem = (props: {
  value?: GroupEntity[];
  onChange?: (value: GroupEntity[]) => void;
}) => {
  const { value = [], onChange } = props;
  const [options, setOptions] = useState<ITreeData[]>([]);
  const [loading, setLoading] = useState<boolean>(true);

  const initTenantOptions = async () => {
    try {
      const tenantOptions = await getTenantOptions();
      setOptions(tenantOptions.map((item) => ({
        key: item.value,
        title: item.label,
        checkable: false,
        selectable: false,
        pKey: '',
        pTitle: ''
      })));
    } catch (error) {
    } finally {
      setLoading(false)
    }
  }

  const onLoadData = (tenantId: string, tenantName: string) => {
    return new Promise<void>((resolve, reject) => {
      getRoleOptions(tenantId).then((data) => {
        const newOptions = options.concat([]);
        const index = newOptions.findIndex((item) => item.key === tenantId);
        newOptions[index].children = data.map((item) => ({
          key: item.value,
          title: item.label,
          checkable: true,
          selectable: false,
          isLeaf: true,
          pKey: tenantId,
          pTitle: tenantName
        }))
        setOptions(newOptions)
        resolve();
      }).catch((e) => {
        reject(e)
      })
    });
  }

  useEffect(() => {
    initTenantOptions()
  }, [])

  return (
    <Spin spinning={loading}>
      <div style={{ marginBottom: 6 }}>
        {value.map((item) => <Tag key={item.id}>{item.path}</Tag>)}
      </div>
      <Tree
        checkedKeys={value.map((item) => item.id)}
        checkable
        loadData={({ key, title }) => onLoadData(key as string, title as string)}
        treeData={options}
        onCheck={(_, info) => {
          const { checkedNodes } = info;
          if (onChange) {
            onChange(checkedNodes.map((item) => ({ 
              id: item.key,
              name: item.title, 
              path: `/${item.pTitle}/${item.title}`,
              tenant_id: item.pKey,
              tenant_name: item.pTitle 
            })))
          }
        }}
      />
    </Spin>
  )
}

export const UpdatePasswordForm = () => (
  <>
    <PasswordFrom />
    <ProFormSwitch name='need_renew' label='临时密码' />
  </>
)
